home *** CD-ROM | disk | FTP | other *** search
- Path: sierra.net!usenet
- From: T Colwell <snowbull@sierra.net>
- Newsgroups: comp.lang.c++
- Subject: Does this create memory leak?...
- Date: Thu, 15 Feb 1996 17:35:36 -0800
- Organization: Sierra-Net
- Message-ID: <3123DF68.1677@sierra.net>
- NNTP-Posting-Host: 204.94.232.59
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- The code which follows seams like it would create a memory leak. The CAT class contains member pointers to
- objects on the heap. When you take an existing object at reassign it via an overridden assignment operator to
- a second object of the same type, what happens to the data at the originally pointed-to address? Here's what I
- mean:
-
- *****************************************************
- #include <iostreams.h>
-
- class CAT
- {
- public:
- CAT(); // default constructor
- // copy constructor and destructor intentionally excluded!
- int GetAge() const { return *itsAge; }
- int GetWeight() const { return *itsWeight; }
- void SetAge(int age) { *itsAge = age; }
- CAT operator=(const CAT &);
-
- private:
- int *itsAge;
- int *itsWeight;
- };
-
- CAT::CAT()
- {
- itsAge = new int;
- itsWeight = new int;
- *itsAge = 5;
- *itsWeight = 9;
- }
-
-
- CAT CAT::operator=(const CAT & rhs)
- {
- if (this == &rhs)
- return *this;
- itsAge = new int;
- itsWeight = new int;
- *itsAge = rhs.GetAge();
- *itsWeight = rhs.GetWeight();
- }
-
-
- void main()
- {
- CAT frisky;
- frisky.SetAge(6);
- CAT whiskers;
- whiskers = frisky; // <--doesn't this leave
- // the old members of whiskers
- // stranded in the heap?
- }
- **************************************************
-
- The assignment operator reinitializes itsAge and itsWeight to point to new heap addresses, what happens to the
- addresses they were pointing to before? Doesn't this create stranded addresses (leaks)?
-
-
- Thanks in advance!
-
- -Tyler Colwell
-